package com.thd.springboottest.security.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * com.thd.springboottest.security.controller.SecurityController
 *
 * @author: wanglei62
 * @DATE: 2022/6/21 16:32
 **/
@Controller
@RequestMapping("/security")
public class SecurityController {
    @RequestMapping("/test")
    @ResponseBody
    public ResponseEntity<String> test(){
        System.out.println("SUCCESS");
        return ResponseEntity.ok("SUCCESS");
    }

    @RequestMapping("/info")
    @ResponseBody
    public ResponseEntity<Authentication> info() throws Exception{
        System.out.println("SUCCESS");
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        ObjectMapper mapper = new ObjectMapper();
        System.out.println(mapper.writeValueAsString(authentication));
        return ResponseEntity.ok(authentication);
    }


    @PreAuthorize("hasRole('admin')")
    @RequestMapping("/testRoleAdmin")
    @ResponseBody
    public ResponseEntity<String> testRoleAdmin(){
        System.out.println("SUCCESS");
        return ResponseEntity.ok("SUCCESS");
    }

    @PreAuthorize("hasAnyRole('admin','user')")
    @RequestMapping("/testRoleAdminOrUser")
    @ResponseBody
    public ResponseEntity<String> testRoleAdminOrUser(){
        System.out.println("SUCCESS");
        return ResponseEntity.ok("SUCCESS");
    }

    @PreAuthorize("hasAuthority('del')")
    @RequestMapping("/testAuthorityDel")
    @ResponseBody
    public ResponseEntity<String> testAuthorityDel(){
        System.out.println("SUCCESS");
        return ResponseEntity.ok("SUCCESS");
    }

    @PreAuthorize("hasAnyAuthority('del','query')")
    @RequestMapping("/testAuthorityDelOrQuery")
    @ResponseBody
    public ResponseEntity<String> testAuthorityDelOrQuery(){
        System.out.println("SUCCESS");
        return ResponseEntity.ok("SUCCESS");
    }

    @PreAuthorize("hasAnyAuthority('sys:del')")
    @RequestMapping("/testAuthorityTree")
    @ResponseBody
    public ResponseEntity<String> testAuthorityTree(){
        System.out.println("SUCCESS");
        return ResponseEntity.ok("SUCCESS");
    }



}
